<?php

namespace Biz\service\BrandRights;

use Biz\cache\brand\LevelRights as cLevelRights;
use Biz\model\brandRights\BrandLevelRightsConfig as mBrandLevelRightsConfig;
use Biz\model\brandRights\BrandLevelRightsLog as mBrandLevelRightsLog;
use Biz\model\brandRights\BrandLevelRightsSource as mBrandLevelRightsSource;
use Biz\model\brandRights\BrandRightsSource as mBrandRightsSource;
use Biz\pockets\constInterface\BrandLevel;
use Biz\pockets\serviceTrait\_Async;

class BrandLevelRightsConfigService implements BrandLevel
{
    use _Async;

    /**
     * 获取等级权益配置
     * @param int $level
     * @return array
     */
    public static function getLevelRightsConfig($level, $status = null)
    {
        $configArr = [];
        $result = mBrandLevelRightsConfig::getRightsConfigByLevel($level, $status);
        if ($result && is_array($result)) {
            $configArr = $result;
        }
        return $configArr;
    }

    /**
     * 获取等级某个权益配置
     * @param int $level
     * @return array
     */
    public static function getLevelOneRightsConfig($level, $rightsSourceId, $status = null)
    {
        $configArr = [];
        $result = mBrandLevelRightsConfig::getOneRightsConfig($level, $rightsSourceId, $status);
        if ($result && is_array($result)) {
            $configArr = $result;
        }
        return $configArr;
    }

    /**
     * 设置等级权益配置
     * @param int $level
     * @param array $configArr
     * @return int
     */
    public static function setLevelRightsConfig($level, $configArr)
    {
        $insertData = [];

        $updateData = [];

        $delData = [];

        $configMap = array_column($configArr, null, 'rights_source_id');

        $levelRightsConfigs = self::getLevelRightsConfig($level);
        if (!empty($levelRightsConfigs)) {
            foreach ($levelRightsConfigs as $levelRightsConfig) {
                if (isset($configMap[$levelRightsConfig['rights_source_id']])) {
                    $updateData[] = [
                        [
                            'rights_data' => $config['rights_data'] ?? 0,
                            'status' => mBrandLevelRightsConfig::STATUS_NORMAL,
                            'edittime' => date('Y-m-d H:i:s', time()),
                        ],
                        ['id' => $levelRightsConfig['id']],
                    ];
                    unset($configMap[$levelRightsConfig['rights_source_id']]);
                    continue;
                }
                $delData[] = [
                    [
                        'status' => mBrandLevelRightsConfig::STATUS_DELETE,
                        'edittime' => date('Y-m-d H:i:s', time()),
                    ],
                    [
                        'id' => $levelRightsConfig['id']
                    ]
                ];

            }
        }

        foreach ($configMap as $rightsSourceId => $config) {
            $insertData[] = [
                'level' => $level,
                'rights_source_id' => $rightsSourceId,
                'rights_data' => $config['rights_data'] ?? 0,
                'status' => mBrandLevelRightsConfig::STATUS_NORMAL,
                'addtime' => date('Y-m-d H:i:s', time()),
                'edittime' => date('Y-m-d H:i:s', time()),
            ];
        }

        $bResult = mBrandLevelRightsConfig::action(function () use ($insertData, $updateData, $delData) {
            foreach ($delData as $item) {
                [$data, $where] = $item;
                $result = mBrandLevelRightsConfig::dataUpdate($data, $where);
                if (!$result) {
                    return false;
                }
            }
            foreach ($updateData as $item) {
                [$data, $where] = $item;
                $result = mBrandLevelRightsConfig::dataUpdate($data, $where);
                if (!$result) {
                    return false;
                }
            }
            if (!empty($insertData)) {
                $result = mBrandLevelRightsConfig::dataMultiInsert($insertData);
                if (!$result) {
                    return false;
                }
            }
            return true;
        });

        return $bResult ? true : false;
    }


    /**
     * 开启关闭单个等级权益
     * @param int $level
     * @param int $rightsSourceId
     * @param int $status
     * @return boolean
     */
    public static function setOneLevelRightsConfig($level, $rightsSourceId, $status = 0)
    {
        $status = $status ? mBrandLevelRightsConfig::STATUS_NORMAL : mBrandLevelRightsConfig::STATUS_DELETE;
        $rightsData = 0;
        $result = false;
        $rightsConfig = self::getLevelOneRightsConfig($level, $rightsSourceId);
        if ($rightsConfig && is_array($rightsConfig)) {
            $updateData = [
                'rights_data' => $rightsData,
                'status' => $status,
                'edittime' => date('Y-m-d H:i:s', time()),
            ];
            $where['id'] = $rightsConfig['id'];
            $result = mBrandLevelRightsConfig::dataUpdate($updateData, $where) > 0;
        } else {
            $insertData = [
                'level' => $level,
                'rights_source_id' => $rightsSourceId,
                'rights_data' => $rightsData,
                'status' => $status,
                'addtime' => date('Y-m-d H:i:s', time()),
                'edittime' => date('Y-m-d H:i:s', time()),
            ];
            $result = mBrandLevelRightsConfig::dataInsert($insertData) > 0;
        }
        return $result;
    }

    /**
     * 设置单个等级权益数量
     * @param int $level
     * @param int $rightsSourceId
     * @param int $rightsData
     * @return boolean
     */
    public static function setOneLevelRightsConfigCount($level, $rightsSourceId, $rightsData = 0)
    {
        $result = false;
        $rightsConfig = self::getLevelOneRightsConfig($level, $rightsSourceId);
        if ($rightsConfig && is_array($rightsConfig)) {
            $updateData = [
                'rights_data' => $rightsData ?? 0,
                'edittime' => date('Y-m-d H:i:s', time()),
            ];
            $where['id'] = $rightsConfig['id'];
            $result = mBrandLevelRightsConfig::dataUpdate($updateData, $where);
        }
        return $result;
    }


    /**
     * 等级权益配置信息
     * @param int $level
     * @param array $filter
     * @return array
     */
    public static function levelSourceRightsConfig($level, $filter = [])
    {
        $sourceRightsAll = [];

        #等级已配置权益
        $levelRightsConfig = mBrandLevelRightsConfig::dataSelect([
            'level' => $level,
            'status' => mBrandLevelRightsConfig::STATUS_NORMAL
        ]);
        $levelRightsConfigMap = !empty($levelRightsConfig) ? array_column($levelRightsConfig, null,
            'rights_source_id') : [];
        #等级权益源
        $levelSourceRights = mBrandLevelRightsSource::dataSelect(['data_status' => mBrandLevelRightsSource::STATUS_NORMAL]);
        $levelRightsIds = empty($levelSourceRights) ? [] : array_column($levelSourceRights, 'source_rights_id');
        if (empty($levelRightsIds)) {
            return $sourceRightsAll;
        }
        $levelSourceRights = array_column($levelSourceRights, null, 'source_rights_id');
        #权益源
        $where['ORDER'] = ['sort_weight' => 'ASC'];
        $where['data_status'] = mBrandRightsSource::STATUS_NORMAL;
        $where['id'] = $levelRightsIds;
        $rights_on = isset($filter['rights_on']) ? $filter['rights_on'] : null;
        unset($filter['rights_on']);
        $where = array_merge($where, $filter);
        $sourceRightsAll = mBrandRightsSource::selectList($where);
        foreach ($sourceRightsAll as $key => $sourceRights) {
            if (isset($levelSourceRights[$sourceRights['id']])) {
                $levelSourceRightsOne = $levelSourceRights[$sourceRights['id']];
                $sourceRightsAll[$key]['rights_title'] = $levelSourceRightsOne['rights_title'];
                $sourceRightsAll[$key]['rights_desc'] = $levelSourceRightsOne['rights_desc'];
            }
            $sourceRightsAll[$key]['rights_data'] = isset($levelRightsConfigMap[$sourceRights['id']]) ?
                $levelRightsConfigMap[$sourceRights['id']]['rights_data'] : 0;
            $sourceRightsAll[$key]['rights_on'] = isset($levelRightsConfigMap[$sourceRights['id']]) &&
            $levelRightsConfigMap[$sourceRights['id']]['status'] == mBrandLevelRightsConfig::STATUS_NORMAL ? 1 : 0;
            if (isset($rights_on)) {
                if ($sourceRightsAll[$key]['rights_on'] != $rights_on) {
                    unset($sourceRightsAll[$key]);
                }
            }
        }
        return $sourceRightsAll;
    }

    /**
     * 获取可获得权益的等级
     * @param int $brandId
     * @param array $rightsIds
     * @param int $brandLevel
     * @param array $rightsMinLevels
     * @return array
     */
    public static function getRightsLevels($brandId, $rightsIds, $brandLevel, $rightsMinLevels)
    {
        $levelRightsConfigs = [];
        $aResult = mBrandLevelRightsConfig::dataSelect([
            'rights_source_id' => $rightsIds,
            'status' => mBrandLevelRightsConfig::STATUS_NORMAL
        ]);
        if ($aResult && is_array($aResult)) {
            $levelRightsConfigs = $aResult;
        }
        $returnData = [];
        $levelData = [];
        if (empty($levelRightsConfigs)) {
            return $returnData;
        }
        $sourceRightsIds = array_column($levelRightsConfigs, 'rights_source_id');
        $sourceRightsMap = BrandRightsSourceService::getRightsSourceMap([
            'id' => $sourceRightsIds,
            'data_status' => mBrandRightsSource::STATUS_NORMAL
        ]);

        $logWhere['brand_id'] = $brandId;
        $logWhere['rights_status'] = mBrandLevelRightsLog::STATUS_NORMAL;
        $lvRightsLogs = mBrandLevelRightsLog::dataSelect($logWhere);
        foreach ($lvRightsLogs as $key => $log) {
            $lvRightsLogs[$key]['index'] = $log['level'] . '_' . $log['rights_source_id'];
        }
        $lvRightsLogs = !empty($lvRightsLogs) ? array_column($lvRightsLogs, null, 'index') : [];
        foreach ($levelRightsConfigs as $key => $item) {
            if (!isset($sourceRightsMap[$item['rights_source_id']])) {
                continue;
            }
            $levelName = self::BRAND_LEVELS[$item['level']];
            $rightsType = $sourceRightsMap[$item['rights_source_id']]['rights_type'];
            $rightsName = $sourceRightsMap[$item['rights_source_id']]['rights_name'];
            $params[0] = $levelName;
            $text = null;
            if (in_array($rightsType,
                [mBrandRightsSource::RIGHTS_TYPE_LIMIT_NUM, mBrandRightsSource::RIGHTS_TYPE_NUM])) {
                $params[1] = intval($item['rights_data']);
                if ($params[1] >= mBrandRightsSource::COUNT_UNLIMIT) {
                    $text = $levelName . '｜不限。';
                }
            }
            if ('put_content' == $rightsName) {//内容投放
                $text = empty($text) ? sprintf(self::PUT_CONTENT_CONDITIONS[$item['level']], ...$params) : $text;
            } else {
                $text = empty($text) ? sprintf(self::LEVEL_RIGHTS_TYPE_CONDITIONS[$rightsType], ...$params) : $text;
            }
            $index = $item['level'] . '_' . $item['rights_source_id'];
            $state = $brandLevel >= $rightsMinLevels[$item['rights_source_id']] && !empty($lvRightsLogs) && isset($lvRightsLogs[$index]) ? '1' : '0';
            $levelData[$item['rights_source_id']][] = [
                'rights_condition_text' => $text,
                'state' => $state,
                'level' => $item['level'],
            ];
        }

        //按等级升序排序
        foreach ($levelData as $rightsId => $levelCons) {
            array_multisort(array_column($levelCons, 'level'), SORT_ASC, $levelCons);
            $rightsType = $sourceRightsMap[$rightsId]['rights_type'];
            if ($rightsType == mBrandRightsSource::RIGHTS_TYPE_OPEN) {
                $returnData[$rightsId] = [$levelCons[0]];
            } else {
                $returnData[$rightsId] = $levelCons;
            }
        }

        return $returnData;
    }


    public static function changeConfig($data)
    {
        $brand = $data['brand'];
        $level = $data['level'];
        $rightsSourceId = $data['rights_source_id'];
        $rightsNum = $data['rights_num'];
        $rightsType = $data['rights_type'];
        $rightsStatus = $data['rights_status'];
        list($result, $msg) = BrandLevelRightsService::brandLevelRightsUpdate($brand, $level, $rightsSourceId, $rightsType, $rightsNum,
            $rightsStatus);
        return [$result, $msg];
    }

    /**
     * 获取权益的最低等级
     * @return array
     */
    public static function getRightsMinLevel()
    {
        $rightsMinLevel = cLevelRights::getRightsMinLevel();

        if ($rightsMinLevel && !empty($rightsMinLevel)) {
            return $rightsMinLevel;
        }

        $rightsMinLevel = [];

        $allLevelRightsCfg = mBrandLevelRightsConfig::dataSelect(['status' => mBrandLevelRightsConfig::STATUS_NORMAL]);
        foreach ($allLevelRightsCfg as $cfg) {
            if (!isset($rightsMinLevel[$cfg['rights_source_id']])) {
                $rightsMinLevel[$cfg['rights_source_id']] = $cfg['level'];
            } else {
                $rightsMinLevel[$cfg['rights_source_id']] = $cfg['level'] < $rightsMinLevel[$cfg['rights_source_id']] ? $cfg['level'] : $rightsMinLevel[$cfg['rights_source_id']];
            }
        }

        cLevelRights::setRightsMinLevel($rightsMinLevel);

        return $rightsMinLevel;
    }

}